<template>
    <el-dialog :close-on-click-modal="false"  ref="dialogform" v-if="dialogVisible" :title="addEditName + title" :visible.sync="dialogVisible"
        width="50%" :before-close="handleClose">
        <el-form :disabled="addEditFlag == 'lookView'" :model="ruleForm" :rules="rules" ref="ruleForm"
            label-width="120px" class="demo-ruleForm">
            <el-form-item v-show="addEditFlag !== 'lookView'" label="处方名称" prop="prescriptionName">
                <el-input v-model="ruleForm.prescriptionName" class="w100p" clearable placeholder="请输入处方名称"></el-input>
            </el-form-item>
            <el-form-item v-show="addEditFlag !== 'lookView'" label="针对疾病" prop="diseaseRecordId">
                <el-select @change="getDiseaseName" v-model="ruleForm.diseaseRecordId" class="w100p" clearable
                    filterable placeholder="请选择疾病">
                    <!-- 疾病名称+批次名称+设施名称+发现人+发现时间组合 -->
                    <el-option v-for="item, index in diseaseList" :key="index"
                        :label="`${item.diseaseName}-${item.batchName}-${item.facilityName}-${item.staffName}-${item.happenTime}`"
                        :value="item.diseaseRecordId"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="用药次数" prop="days">
                <el-input @change="handleGetDays" v-model="ruleForm.days" class="w100p" clearable
                    placeholder="请输入用药次数"></el-input>
            </el-form-item>
            <el-form-item label="注意事项" prop="attentionMatter">
                <el-input v-model="ruleForm.attentionMatter" class="w100p" clearable placeholder="请输入注意事项"></el-input>
            </el-form-item>
            <el-form-item label="处方信息" prop="detailDaysList">
                <div class="detailDaysInfo"
                    v-for="day, dayIndex in Array.from({ length: ruleForm.days }, (_, i) => i + 1)" :key="dayIndex">
                    <div class="useDays">
                        <span class="label">用药第{{ day }}次</span>
                        <el-button type="text" @click="addList(day)">添加</el-button>
                    </div>
                    <el-row v-show="day == item.days" v-for="item, index in ruleForm.detailDaysList" :key="index">
                        <el-col :span="8">
                            <el-form-item :prop="`detailDaysList[${index}][materialNo]`" :rules="rules.materialNo">
                                <el-select @change="handleChangeUnit($event, index)" clearable filterable class=" w100p"
                                    v-model="item.materialNo" placeholder="请选择药品">
                                    <el-option
                                        v-if="m.materialTypeNo == '1077222993386450944' || m.materialTypeNo == '4165464165465146516'"
                                        v-for="m, i in materialList" :key="i" :label="m.materialName"
                                        :value="m.materialNo"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item :prop="`detailDaysList[${index}][usage]`">
                                <el-input v-model="item.usage" class="w100p" clearable placeholder="请输入用法"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="10">
                            <el-form-item :prop="`detailDaysList[${index}][num]`" :rules="rules.num">
                                <el-input type="number" @change="(e) => { item.num = Number(e).toFixed(2) }"
                                    v-model="item.num" class="w100p" clearable placeholder="请输入用量">
                                    <template slot="append">
                                        <span v-show="item.unitName">{{ item.unitName }}/平方米</span>
                                    </template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <div class="btnList" v-show="addEditFlag !== 'lookView'">
                                <el-button class="delBtn" type="text" v-if="ruleForm.detailDaysList.length > 1"
                                    @click="delList(index)">删除</el-button>
                            </div>
                        </el-col>
                    </el-row>
                </div>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button type="primary" v-show="addEditFlag !== 'lookView'" @click="submitForm">确 定</el-button>
        </span>
    </el-dialog>
</template>
<script>
import prescription from '@/api/healthManagement/prescription.js';
export default {
    components: {},
    props: {
        addEditFlag: {
            type: String,
            default: () => {
                return 'add'
            }
        },
        data: {
            type: Object,
            default: () => {
                return {}
            }
        },
        title: {
            type: String,
            default: () => {
                return '操作表单'
            }
        },
        dialogVisible: {
            type: Boolean,
            default: () => {
                return false
            }
        },
        materialList: {
            type: Array,
            default: () => {
                return []
            }
        },
        diseaseList: {
            type: Array,
            default: () => {
                return []
            }
        },
    },
    data() {
        let validator = function (rule, value, callback) {
            if (value > 0) {
                callback()
            } else {
                callback(new Error('请输入大于0的数值！'))
            }
        }
        let validator_days = function (rule, value, callback) {
            if (value > 0 && value % 1 == 0) {
                callback()
            } else {
                callback(new Error('请输入大于0的数值！'))
            }
        }
        return {
            addEditName: '添加',
            addEditApi: '',
            ruleForm: {},
            rules: {
                prescriptionName: [
                    { required: true, message: '请输入处方名称', trigger: 'change' }
                ],
                diseaseRecordId: [
                    { required: true, message: '请选择疾病', trigger: 'change' }
                ],
                materialNo: [
                    { required: true, message: '请选择药品', trigger: 'change' }
                ],
                num: [
                    { required: true, validator: validator, trigger: 'change' }
                ],
                detailDaysList: [
                    { required: true, message: '请选择药品', trigger: 'change' }
                ],
                days: [
                    { required: true, validator: validator_days, trigger: 'change' }
                ],
            }
        }
    },
    computed: {

    },
    watch: {
        dialogVisible(v) {
            v && this.initData()
        }
    },

    mounted() { },
    methods: {
        initData() {
            if (this.addEditFlag == 'add') {
                this.resetForm()
                this.ruleForm = {};
                this.addEditApi = prescription.add
                this.addEditName = '添加'
            } else if (this.addEditFlag == 'edit' || this.addEditFlag == 'lookView') {
                this.ruleForm = { ...this.data }
                this.addEditApi = prescription.edit
                this.addEditName = this.addEditFlag == 'lookView' ? '查看' : '编辑'
            }
            let detailDaysList = []
            if (!this.ruleForm.detailList || !this.ruleForm.detailList.length) {
                detailDaysList = []
            } else {
                this.ruleForm.detailList.forEach( item=> {
                    detailDaysList.push(item)
                })
            }
            if (!this.ruleForm.days) {
                this.$set(this.resetForm, 'days', 1);
            }
            console.log(detailDaysList)
            if (!detailDaysList.length) {
                this.$set(this.ruleForm, 'detailDaysList', [])
                this.addList(1)
            } else {
                this.$set(this.ruleForm, 'detailDaysList', detailDaysList)
            }
        },
        handleGetDays(e) {
            if (e > 10) {
                this.$confirm(`此操作将创建${e}次用药记录,请确认继续该操作?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.getDays(e)
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消'
                    });
                });
            }else{
                this.getDays(e)
            }
        },
        getDays(e){
            let length = Array.from({ length: e }, (_, i) => i + 1);
            console.log(length)
            length.forEach(day => {
                let rut = this.ruleForm.detailDaysList.find(item => {
                    return item.days == day
                })
                console.log(day)
                if (!rut) {
                    this.addList(day)
                }
            });
        },
        getDiseaseName(e) {
            let rut = this.diseaseList.find(item => {
                return item.diseaseRecordId == e
            })

            this.$set(this.ruleForm, 'diseaseName', `${rut.diseaseName}-${rut.batchName}-${rut.facilityName}-${rut.staffName}-${rut.happenTime}`)
            this.$set(this.ruleForm, 'diseaseRecordId', e)
        },
        handleChangeUnit(e, index) {
            let rut = this.materialList.find(item => {
                return item.materialNo == e
            })
            let detail = this.ruleForm.detailDaysList[index]
            this.$set(this.ruleForm.detailDaysList, index, {
                ...detail,
                ...rut
            })
        },
        delList(index) {
            let detail = this.ruleForm.detailDaysList[index];
            let days = detail.days;
            let filterList = this.ruleForm.detailDaysList.filter(e => e.days == days);
            if (filterList.length == 1) {
                this.$message.warning('治疗记录至少保留一次')
                return
            }
            let list = JSON.parse(JSON.stringify(this.ruleForm.detailDaysList));
            list.splice(index, 1);
            this.$set(this.ruleForm, 'detailDaysList', list)
        },
        addList(day) {
            let list = JSON.parse(JSON.stringify(this.ruleForm.detailDaysList || []));
            let index = list.length;
            list[index] = {
                materialName: '',
                materialNo: '',
                num: '',
                days: day,
                unitName: ''
            }
            this.$set(this.ruleForm, 'detailDaysList', list)
        },
        getDetailList() {
            let list = this.ruleForm.detailDaysList;
            let datObj = {};
            let detailList = [];
            list.forEach(e => {
                if (!datObj[e.days]) {
                    datObj[e.days] = []
                }
                datObj[e.days] = datObj[e.days].concat(e)
            })
            for (let key in datObj) {
                detailList.push(datObj[key])
            }
            console.log(detailList);
            this.$set(this.ruleForm, 'detailList', detailList)
        },
        //提交表单
        submitForm() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.getDetailList();
                    this.addEditApi({ ...this.ruleForm }).then(res => {
                        let msg = res.code == 1 ? '操作成功' : '操作失败'
                        this.$message[res.code == 1 ? 'success' : 'warning'](res.msg || msg)
                        res.code == 1 && this.cancel();
                    }).catch(err => {
                        console.log(err)
                    })
                } else {
                    return false;
                }
            })
        },
        //重置
        resetForm() {
            this.ruleForm = {};
            this.$refs.ruleForm && this.$refs.ruleForm.resetFields()
        },
        //取消关闭
        cancel() {
            this.$emit("closeDialog")
            this.resetForm()
        },
        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => { this.resetForm(); this.cancel() })
                .catch(_ => { });
        }
    }
};
</script>
<style lang="scss" scoped>
.btnList {
    width: 100%;
    padding: 0 20px;

    .delBtn {
        color: #ff0000;
    }
}

::v-deep .el-input.is-disabled .el-input__inner {
    background-color: none;
}

.detailDaysInfo {
    padding: 10px;
    background-color: #f3f3f3;
    margin-top: 10px;

    .useDays {
        font-weight: bold;

        .label {
            padding: 0 10px;
        }
    }
}
</style>